/**
 * 
 */
package fb.chatter.utils;

import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;


/**
 * @author hoannguyen
 *
 */
public final class JSONUtils {

	/**
	 * To convert from an object to a JSON string
	 * 
	 * @param object
	 * @return
	 */
	public static String convertObjectToJSON(Object object){
		
		String jsonString = "";
		
		ObjectMapper mapper = new ObjectMapper();
		try {
			jsonString = mapper.writeValueAsString(object);
		} catch (JsonGenerationException e) {
			ExceptionUtils.log(e);
		} catch (JsonMappingException e) {
			ExceptionUtils.log(e);
		} catch (IOException e) {
			ExceptionUtils.log(e);
		}
				
		return jsonString;
	}
	
	/**
	 * To convert from the given JSON string to the given class object
	 * 
	 * @param json
	 * @param clazz
	 * @return
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static Object conveJSONToObject(String json, Class clazz){
		
		Object obj = null;
		
		ObjectMapper mapper = new ObjectMapper();
		mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		try {
			obj = mapper.readValue(json, clazz);
		} catch (JsonParseException e) {
			ExceptionUtils.log(e);
		} catch (JsonMappingException e) {
			ExceptionUtils.log(e);
		} catch (IOException e) {
			ExceptionUtils.log(e);
		}
		
		return obj;
	}
}
